package com.hantanger.weblog.xmlrpc.handler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Text;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.photos.PhotoEntry;
import com.hantanger.weblog.dao.CategoryDao;
import com.hantanger.weblog.model.Category;
import com.hantanger.weblog.model.Post;
import com.hantanger.weblog.service.PicasaService;
import com.hantanger.weblog.service.PostService;
import com.hantanger.weblog.service.UserService;
import com.hantanger.weblog.util.ClassFactory;
import com.hantanger.weblog.util.HtmlUtil;
import com.hantanger.weblog.util.TagUtil;

public class MetaWeblogHandler {

	protected PostService getPostService() {
		return ClassFactory.getInstance(PostService.class);
	}
	
	public CategoryDao getCategoryDao() {
		return ClassFactory.getInstance(CategoryDao.class);
	}

	public UserService getUserService() {
		return ClassFactory.getInstance(UserService.class);
	}

	public String getSpaceUrl() {
		return getUserService().getDefaultSetting().getSpaceUrl();
	}

	private PicasaService getPicasaService() {
		return ClassFactory.getInstance(PicasaService.class);
	}

	// blogger api
	public List<Map<String, Object>> getUsersBlogs(String appkey, String email,
			String password) {
		if(getUserService().getUserId(email, password) <= 0){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String spaceUrl = getSpaceUrl();
		map.put("url", spaceUrl);
		map.put("blogid", "0");
		map.put("isAdmin", true);
		map.put("blogName", getUserService().getDefaultSetting().getSpaceName());
		map.put("xmlrpc", spaceUrl + "xmlrpc/metaweblog/");
		list.add(map);
		return list;
	}

	public List<Map<String, Object>> getUserInfo(String appkey, String email,
			String password) {
		if(getUserService().getUserId(email, password) <= 0){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		map.put("userid", "1");
		map.put("url", getSpaceUrl());
		map.put("nickname", getUserService().getDefaultSetting().getSpaceName());
		list.add(map);
		return list;
	}
	
	public boolean deletePost(String blogId, String postId, String email,
			String password, boolean completeDelete){
		if(getUserService().getUserId(email, password) <= 0){
			return false;
		}
		return true;
	}

	// metaweblog api
	public String newPost(String blogId, String email, String password,
			Map<String, Object> postMap, boolean publish) {
		long userId = getUserService().getUserId(email, password);
		if (userId <= 0) {
			return null;
		}
		long postId = Long.parseLong(blogId);
		Post post = getPostService().getPostById(postId, false);
		if(post == null){
			post = new Post();
		}
		post.setMoveFrom("metaweblog");

		String title = (String) postMap.get("title");
		post.setTitle(HtmlUtil.repairHtml(title));

		String content = (String) postMap.get("description");
		post.setContent(new Text(HtmlUtil.repairHtml(content)));

		List<String> tags = TagUtil.processTag((String) postMap
				.get("mt_keywords"));
		post.setTags(tags);

		String keyword = "";
		post.setKeyword(keyword);

		post.setPubliced(true);
		post.setAllowComment(true);

		long categoryId = -1;

		@SuppressWarnings("unchecked")
		List<String> categories = (List<String>)postMap.get("categories");
		if(categories != null && categories.size() > 0){
			String categoryName = categories.get(0);
			String[] parentSub = categoryName.split(Category.SEP);
			String parentName = null;
			String subName = parentSub[0];
			if(parentSub.length == 2){
				parentName = parentSub[0];
				subName = parentSub[1];
			}
			Category category = getCategoryDao().getCategoryByParentName(subName, parentName);
			if(category != null){
				categoryId = category.getId();
			}
		}
		if(categoryId == -1){
			categoryId = getCategoryDao().getDefCategory().getId();
		}

		post.setCategoryId(categoryId);

		post.setPublished(publish);

		post.setAuthorId(userId);
		getPostService().insert(post);
		return post.getId() + "";
	}

	public boolean editPost(String blogId, String email, String password,
			Map<String, Object> post, boolean publish) {
		if(getUserService().getUserId(email, password) <= 0){
			return false;
		}
		String postId = newPost(blogId, email, password, post, publish);
		if(postId == null){
			return false;
		}
		return true;
	}

	public Map<String, Object> getPost(String blogId, String email,
			String password) {
		Post post = getPostService().getPostById(Long.parseLong(blogId), false);
		return post2Map(post);
	}

	public List<Map<String, Object>> getRecentPosts(String blogId,
			String email, String password, int numPosts) {
		if(getUserService().getUserId(email, password) <= 0){
			return null;
		}
		List<Map<String, Object>> posts = new ArrayList<Map<String, Object>>();
		List<Post> postList = getPostService().getPosts(numPosts,
				System.currentTimeMillis(), false);
		if (postList != null) {
			for (Post post : postList) {
				posts.add(post2Map(post));
			}
		}
		return posts;
	}

	private Map<String, Object> post2Map(Post post) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (post == null) {
			return map;
		}
		map.put("title", post.getTitle());
		map.put("description", post.getContent().getValue());
		map.put("postid", post.getId());
		map.put("dateCreated", new Date(post.getPublishTime()));
		map.put("publish", post.isPublished());
		map.put("mt_excerpt", (post.getDigest()==null)?"":post.getDigest().getValue());
		map.put("mt_keywords", (post.getTags()==null)?Collections.EMPTY_LIST:post.getTags());

		List<String> categories = new ArrayList<String>();
		categories.add(post.getCategory().getName());
		map.put("categories", categories);
		return map;
	}

	public Map<String, Object> newMediaObject(String blogId, String email,
			String password, Map<String, Object> object) {
		if(getUserService().getUserId(email, password) <= 0){
			return null;
		}
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			byte[] bits = (byte[]) object.get("bits");
			String title = (String) object.get("name");
			PhotoEntry photoEntry = getPicasaService().insertPhoto(bits, title);
			if (photoEntry != null) {
				String url = ((MediaContent) photoEntry.getContent()).getUri();
				res.put("url", url);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public List<Map<String, Object>> getCategories(String blogId, String email,
			String password) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<Category> categories = getPostService().getAllCategorys();
		Map<Long, Category> catMap = new HashMap<Long, Category>();
		for (Category category : categories) {
			catMap.put(category.getId(), category);
		}
		for (Category category : categories) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("description", "");
			String catName = category.getName();
			if(category.getParentId() > 0){
				Category parentCategory = catMap.get(category.getParentId());
				if(parentCategory != null){
					catName = parentCategory.getName() + "--" + catName;
				}
			}
			map.put("title", catName);
			list.add(map);
		}
		return list;
	}

}
